package com.yanxinim.cn.store.adapter;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.yanxinim.cn.AppConfig;
import com.yanxinim.cn.R;
import com.yanxinim.cn.store.Goods;
import com.yanxinim.cn.store.bean.CartInfo;
import com.yanxinim.cn.util.ImageLoadTool;
import com.yanxinim.cn.util.ToastUtil;
import com.yanxinim.cn.view.LoadingDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


public class StoreCartAdapter extends RecyclerView.Adapter<StoreCartAdapter.ViewHolder> {


    private Context mContext;
    private List<CartInfo> goodsTypeItemsInfos = new ArrayList<>();
    private List<CartInfo> selectedList = new ArrayList<>();
    private AdapterOnClickListener adapterOnClickListener;
    private double allTotal;
    private String userId;
    private SelectedListener selectedListener;
    private LoadingDialog loadingDialog;
    public AdapterOnClickListener getAdapterOnClickListener() {
        return adapterOnClickListener;
    }

    public List<CartInfo> getSelectedList() {
        return selectedList;
    }

    public void setSelectedListener(SelectedListener selectedListener) {
        this.selectedListener = selectedListener;
    }

    public void setAdapterOnClickListener(AdapterOnClickListener adapterOnClickListener) {
        this.adapterOnClickListener = adapterOnClickListener;
    }

    public StoreCartAdapter(Context mContext, List<CartInfo> goodsTypeItemsInfos,String userId) {
        this.mContext = mContext;
        this.goodsTypeItemsInfos = goodsTypeItemsInfos;
        this.userId = userId;
        loadingDialog = new LoadingDialog(mContext);
    }

    public void addAllData(List<CartInfo> goodsItems) {
        goodsTypeItemsInfos.addAll(goodsItems);
        notifyItemRangeChanged(goodsTypeItemsInfos.size() - goodsItems.size(), goodsItems.size());
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_cart_adapter, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, @SuppressLint("RecyclerView") int i) {
        CartInfo goods = goodsTypeItemsInfos.get(i);
        ImageLoadTool.imageLoad(mContext, goods.getProductLogo(), viewHolder.ivGoodsImage);
        viewHolder.tvGoodsName.setText(goods.getProductName());
        viewHolder.tvGoodsMoney.setText(goods.getProductMoney());
        viewHolder.tvGoodsDesc.setVisibility(View.GONE);
        viewHolder.tvNum.setText(goods.getProductNum());
        if (goods.isSelected()) {
            viewHolder.ivSelected.setImageResource(R.drawable.bg_radio_blu);
            if (!selectedList.contains(goods))
                selectedList.add(goods);
        } else {
            viewHolder.ivSelected.setImageResource(R.drawable.bg_radio_no);
            if (selectedList.contains(goods))
                selectedList.remove(goods);
        }

        viewHolder.ivSelected.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goods.isSelected()) {
                    goods.setSelected(false);
                    notifyItemChanged(i, goods);
                    if (selectedList.contains(goods))
                        selectedList.remove(goods);
                } else {
                    goods.setSelected(true);
                    notifyItemChanged(i, goods);
                    if (!selectedList.contains(goods))
                        selectedList.add(goods);
                }
                selectedListener.selected(selectedList);
            }
        });
        viewHolder.tvNumAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateCartNum(i,goods.getId(),1);
                String goodsNum = viewHolder.tvNum.getText().toString();
                int num = Integer.parseInt(goodsNum) + 1;
                goods.setProductNum(String.valueOf(num));
                notifyItemChanged(i, goods);
                List<CartInfo> goodsListS = selectedList;
                for (int i = 0; i < goodsListS.size(); i++) {
                    if (goodsListS.get(i).getId().equals(goods.getId())) {
                        selectedList.set(i, goods);
                        break;
                    }
                }
                selectedListener.selected(selectedList);
            }
        });
        viewHolder.tvNumMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String goodsNum = viewHolder.tvNum.getText().toString();
                if (Integer.parseInt(goodsNum)==1) {
                    return;
                }
                updateCartNum(i,goods.getId(),-1);
                int num = Integer.parseInt(goodsNum) - 1;
                goods.setProductNum(String.valueOf(num));
                notifyItemChanged(i, goods);
                List<CartInfo> goodsListS = selectedList;
                for (int i = 0; i < goodsListS.size(); i++) {
                    if (goodsListS.get(i).getId().equals(goods.getId())) {
                        selectedList.set(i, goods);
                        break;
                    }
                }
                selectedListener.selected(selectedList);
            }
        });
        viewHolder.tvGoodsDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delCartData(i, goods.getProductId());
            }
        });
//        viewHolder.itemView.setOnClickListener(v -> adapterOnClickListener.onClick(i, goods));
    }

    public interface AdapterOnClickListener {
        void onClick(int position, Goods data);
    }

    public interface SelectedListener {
        void selected(List<CartInfo> goods);
    }

    @Override
    public int getItemCount() {
        return goodsTypeItemsInfos.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_selected)
        ImageView ivSelected;
        @BindView(R.id.iv_goods_image)
        ImageView ivGoodsImage;
        @BindView(R.id.tv_goods_name)
        TextView tvGoodsName;
        @BindView(R.id.tv_goods_desc)
        TextView tvGoodsDesc;
        @BindView(R.id.tv_goods_del)
        ImageView tvGoodsDel;
        @BindView(R.id.tv_goods_money)
        TextView tvGoodsMoney;
        @BindView(R.id.tv_num_minus)
        TextView tvNumMinus;
        @BindView(R.id.tv_num)
        TextView tvNum;
        @BindView(R.id.tv_num_add)
        TextView tvNumAdd;

        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private void updateCartNum(int position, String cartId,int type) {
        if (loadingDialog != null)
            loadingDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put("cartId",cartId);
        map.put("type", String.valueOf(type));
        map.put("num","1");
        HttpUtils.get().url(AppConfig.STORE_UPDATE_CART_NUM)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (jsonObject.getInteger("resultCode") == 1) {
                                  /*  CartInfo cartInfo = goodsTypeItemsInfos.get(position);

                                    int num = Integer.parseInt(cartInfo.getProductNum()) + 1;
                                    cartInfo.setProductNum(num);
                                    notifyItemChanged(position,cartInfo);*/
                                }else {
//                                    ToastUtil.showToast(mContext,"删除失败");
                                }
                            }
                        });
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }
                });
    }

    private void delCartData(int position, String goodsId) {
        if (loadingDialog != null)
            loadingDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put("productId",goodsId);
        map.put("userId",userId);
        HttpUtils.get().url(AppConfig.STORE_DELETE_CART)
                .params(map)
                .build()
                .execute(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        e.printStackTrace();
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string();
                        JSONObject jsonObject = JSON.parseObject(result);
                        ((Activity)mContext).runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (jsonObject.getInteger("resultCode") == 1) {
                                    if (goodsTypeItemsInfos.size() == 1){
                                        goodsTypeItemsInfos.clear();
                                        notifyDataSetChanged();
                                    }else {
                                        goodsTypeItemsInfos.remove(position);
                                        notifyItemRemoved(position);
                                    }
                                }else {
                                    ToastUtil.showToast(mContext,"删除失败");
                                }
                            }
                        });
                        if (loadingDialog != null)
                            loadingDialog.dismiss();
                    }
                });
    }

    public void removerItem(CartInfo cartInfo){
        if (goodsTypeItemsInfos.size() == 1){
            goodsTypeItemsInfos.clear();
            notifyDataSetChanged();
        }else {
            goodsTypeItemsInfos.remove(cartInfo);
            notifyDataSetChanged();
        }
    }
}
